﻿using System;
using System.IO;
using System.Runtime.Serialization;

namespace ACS.EPCHIS.Utilities.Shared
{
    public class DataContractSerializationUtility
    {
        public static byte[] Serialize<T>(T obj) where T : class
        {
            Type objType = obj.GetType();
            DataContractSerializer serializer = new DataContractSerializer(objType);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                serializer.WriteObject(memoryStream, obj);
                memoryStream.Flush();

                return memoryStream.ToArray();
            }
        }

        public static T Deserialize<T>(byte[] bytes) where T : class
        {
            if (bytes == null) return null;
            Type objType = typeof(T);
            DataContractSerializer serializer = new DataContractSerializer(objType);

            T obj;
            using (MemoryStream memoryStream = new MemoryStream(bytes, false))
            {
                obj = serializer.ReadObject(memoryStream) as T;
            }

            return obj;
        }

        public static string SerializeToString<T>(T obj) where T : class
        {
            Type objType = obj.GetType();
            var serializer = new DataContractSerializer(objType);
            using (var pack = new StringWriter())
            {
                using (var writer = new System.Xml.XmlTextWriter(pack))
                {
                    serializer.WriteObject(writer, obj);
                    return pack.ToString();
                }
            }
        }
    }
}

